<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑工艺' : '新增工艺'"
    width="600px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="工艺编号" prop="craftCode">
        <el-input
          v-model="formData.craftCode"
          placeholder="请输入工艺编号"
        >
          <template #append>
            <el-button 
              @click="generateCode('GY_')" 
              :loading="codeGenerating"
              type="primary"
            >
              生成编码
            </el-button>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="工艺名称" prop="craftName">
        <el-input
          v-model="formData.craftName"
          placeholder="请输入工艺名称"
        />
      </el-form-item>

      <el-form-item label="产品名称" prop="craftProductId">
        <el-select
          v-model="formData.craftProductId"
          placeholder="请选择产品"
          filterable
          clearable
          style="width: 100%"
          :loading="productLoading"
        >
          <el-option
            v-for="product in productList"
            :key="product.id"
            :label="product.productName"
            :value="product.id"
          >
            <div class="product-option">
              <span>{{ product.productName }}</span>
              <span class="product-code">{{ product.productCode }}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="工艺总时长" prop="craftTotalStdTime">
        <el-input-number
          v-model="formData.craftTotalStdTime"
          :min="0"
          :precision="2"
          placeholder="请输入工艺总时长"
          style="width: 100%"
        />
        <span class="unit-tip">小时</span>
      </el-form-item>

      <el-form-item label="工艺描述" prop="craftDescription">
        <el-input
          v-model="formData.craftDescription"
          type="textarea"
          :rows="3"
          placeholder="请输入工艺描述"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        {{ isEdit ? "更新" : "保存" }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch, computed } from "vue";
import { ElMessage } from "element-plus";
import { craftApi } from "@/api/craft";
import { basicProductApi } from "@/api/basicProduct";
import { codeGeneratorApi } from "@/api/codeGenerator";

export default {
  name: "CraftFormDialog",
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    craftData: {
      type: Object,
      default: null,
    },
  },
  emits: ["update:modelValue", "saved"],
  setup(props, { emit }) {
    const formRef = ref();
    const saving = ref(false);
    const productLoading = ref(false);
    const productList = ref([]);
    const codeGenerating = ref(false);

    // 对话框显示状态
    const visible = computed({
      get: () => props.modelValue,
      set: (val) => emit("update:modelValue", val),
    });

    // 是否为编辑模式
    const isEdit = computed(() => {
      return props.craftData && props.craftData.id;
    });

    // 表单数据
    const formData = reactive({
      id: "",
      craftCode: "",
      craftName: "",
      craftProductId: "",
      craftTotalStdTime: null,
      craftDescription: "",
    });

    // 表单验证规则
    const formRules = {
      craftCode: [
        { required: true, message: "请输入工艺编号", trigger: "blur" },
      ],
      craftName: [
        { required: true, message: "请输入工艺名称", trigger: "blur" },
      ],
    };

    // 加载产品列表
    const loadProductList = async () => {
      try {
        productLoading.value = true;
        const response = await basicProductApi.getProductsByCurrentTenant();
        console.log("产品列表加载成功:", response);
        if (response && response.data) {
          productList.value = response.data;
        }
      } catch (error) {
        console.error("加载产品列表失败:", error);
        ElMessage.error("加载产品列表失败: " + (error.message || "未知错误"));
      } finally {
        productLoading.value = false;
      }
    };

    // 监听对话框显示状态，加载产品列表和填充表单
    watch(
      () => props.modelValue,
      (newVal) => {
        if (newVal) {
          loadProductList();
          if (props.craftData) {
            Object.assign(formData, props.craftData);
          } else {
            resetForm();
          }
        }
      },
    );

    // 重置表单
    const resetForm = () => {
      Object.assign(formData, {
        id: "",
        craftCode: "",
        craftName: "",
        craftProductId: "",
        craftTotalStdTime: null,
        craftDescription: "",
      });
      formRef.value?.clearValidate();
    };

    // 生成编码
    const generateCode = async (prefix) => {
      try {
        codeGenerating.value = true;
        const response = await codeGeneratorApi.gen({ prefix });
        if (response && response.data) {
          formData.craftCode = response.data;
          ElMessage.success('编码生成成功');
        } else {
          ElMessage.error('编码生成失败');
        }
      } catch (error) {
        console.error('生成编码失败:', error);
        ElMessage.error('生成编码失败: ' + (error.message || '未知错误'));
      } finally {
        codeGenerating.value = false;
      }
    };

    // 关闭对话框
    const handleClose = () => {
      visible.value = false;
      resetForm();
    };

    // 保存工艺
    const handleSave = async () => {
      try {
        // 表单验证
        await formRef.value.validate();

        saving.value = true;

        let savedData = null;

        if (formData.id) {
          // 更新工艺
          await craftApi.updateCraft(formData);
          ElMessage.success("工艺更新成功");
          // 使用表单数据（编辑模式已有完整数据）
          savedData = { ...formData };
        } else {
          // 创建工艺
          const response = await craftApi.createCraft(formData);
          ElMessage.success("工艺创建成功");
          // 使用服务端返回的数据（包含新生成的ID）
          savedData = response.data || { ...formData };
        }

        // 触发保存事件，传递保存后的数据
        emit("saved", savedData);
        handleClose();
      } catch (error) {
        if (error !== false) {
          // 忽略表单验证失败
          console.error("保存工艺失败:", error);
          ElMessage.error("保存工艺失败: " + (error.message || "未知错误"));
        }
      } finally {
        saving.value = false;
      }
    };

    return {
      formRef,
      visible,
      isEdit,
      formData,
      formRules,
      saving,
      productLoading,
      productList,
      codeGenerating,
      generateCode,
      handleClose,
      handleSave,
    };
  },
};
</script>

<style scoped>
.product-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-code {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}

.unit-tip {
  margin-left: 8px;
  color: #909399;
  font-size: 12px;
}

/* 表单项样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>
